package cn.ffcs.bpmpvc.web;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.echoice.paper.PageBean;
import org.echoice.paper.PageNavi;
import org.echoice.spring.BaseController;
import org.springframework.web.servlet.ModelAndView;

import cn.ffcs.bpm.model.ProcTranRecord;
import cn.ffcs.bpmpvc.services.MeetingProtocolService;
import cn.ffcs.bpmpvc.svc.TaskAssignBean;
import cn.ffcs.bpmpvc.utils.FlowContextUtil;
import cn.ffcs.bpmpvc.web.util.UserContextUtil;
import cn.ffcs.bpmpvc.web.views.ProcessInstView;
import cn.ffcs.bpmpvc.web.views.ProcessView;
import cn.ffcs.bpmpvc.web.views.TaskView;
import cn.ffcs.security.model.User;
import cn.ffcs.share.model.ShareReference;
/**
 * 重点沟通会纪要阅办流程
 * @author wujy
 *分公司重点工作沟通会纪要
 */
public class MeetingProtocolController extends BaseController {
	private MeetingProtocolService meetingProtocolService;
	private final String basePath="/bpm/meetingProtocol/";
	@Override
	public ModelAndView index(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// TODO Auto-generated method stub
		ShareReference searchForm=new ShareReference();
		bindObject(request, searchForm);
		PageBean pageBean=meetingProtocolService.getMeetingProtocolDao().searchMeetingProtocolPage(searchForm, getPageNo(request), getPageSize(request));
		request.setAttribute("dataList", pageBean.getDataList());
		request.setAttribute("pageNaviStr", PageNavi.getPageNaviButton(request, pageBean));
		return new ModelAndView(basePath+"index.jsp");
	}

	public ModelAndView applyInit(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// TODO Auto-generated method stub
		User user =UserContextUtil.getUserContext(request).getCurrUser();
		String processId=meetingProtocolService.getProcessId();
		ProcessView processView=meetingProtocolService.getProcessPvcService().getInitProcessInfo(processId);
		request.setAttribute("processView", processView);
		return new ModelAndView(basePath+"apply_init.jsp");
	}
	
	public ModelAndView saveStartFlow(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// TODO Auto-generated method stub
	    boolean isCommit=FlowContextUtil.isCommit(request);
	    User user =UserContextUtil.getUserContext(request).getCurrUser();
	    List<TaskAssignBean> nextTasksList = FlowContextUtil.getNextTaskUserList(request);
	    String processId=request.getParameter("processId");
	    ShareReference shareReference=new ShareReference();
	    bindObject(request, shareReference);
	    shareReference.setEnd(FlowContextUtil.getEndDate());
	    shareReference.setBegin(new Date());
	    shareReference.setCreator(user.getUserID());
	    
	    String returnMsg=FlowContextUtil.setStartFlowMsg(isCommit);
	    try{
			meetingProtocolService.saveAndStartFlow(processId, user.getPerson(), nextTasksList, isCommit, shareReference, request);
        }catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
            returnMsg="提交失败，原因："+e.getMessage();
        }
	    FlowContextUtil.setReturnMsgAttr(request, returnMsg);
		return new ModelAndView(FlowContextUtil.JSP_SUCCESS);
	}

	public ModelAndView showDetail(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// TODO Auto-generated method stub
		String procInstId=request.getParameter("procinstId");
        String toPage=request.getParameter("toPage");
        String flowTaskId=request.getParameter("flowTaskId");
        TaskView taskView=getMeetingProtocolService().getTaskService().getTaskView(flowTaskId);
        String taskType=taskView.getProcTranRecord().getTaskType();
        Map dataMap=initAppData(request);
        request.setAttribute("taskView", taskView);
        if("03".equalsIgnoreCase(taskType)){
        	//return new ModelAndView(basePath+"showDetail.jsp",dataMap);
        }
        if(StringUtils.isNotBlank(toPage)){
        	return new ModelAndView(basePath+toPage+".jsp",dataMap);
        	//return new ModelAndView(basePath+"showDetail.jsp",dataMap);
        }
		return new ModelAndView(basePath+"showDetail.jsp",dataMap);
	}
	
	public ModelAndView commitTask(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String content=request.getParameter("commentComtent");
		boolean isCommit=FlowContextUtil.isCommit(request);
		String flowTaskId=request.getParameter("flowTaskId");
		List<TaskAssignBean> nextTasksList = FlowContextUtil.getNextTaskUserList(request);
		String returnMsg=FlowContextUtil.setCommitTaskMsg(isCommit);
		try{
			if (isCommit) {
				getMeetingProtocolService().getTaskService().completeTask(flowTaskId, content, nextTasksList);
			} else {
				getMeetingProtocolService().getTaskService().saveTaskAssignUser(flowTaskId, content, nextTasksList);
			}
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			returnMsg="操作失败，原因："+e.getMessage();
		}
		FlowContextUtil.setReturnMsgAttr(request, returnMsg);
		return new ModelAndView(FlowContextUtil.JSP_SUCCESS);
	}
	
	public ModelAndView commitApplyTask(HttpServletRequest request, HttpServletResponse response) throws Exception {
		boolean isCommit=FlowContextUtil.isCommit(request);
		String flowTaskId=request.getParameter("flowTaskId");
		String procinstId=request.getParameter("procinstId");
		String content=request.getParameter("commentComtent");
		List<TaskAssignBean> nextTasksList = FlowContextUtil.getNextTaskUserList(request);
		String returnMsg=FlowContextUtil.setCommitTaskMsg(isCommit);
		ShareReference shareReference=new ShareReference();
	    bindObject(request, shareReference);
		try{
			getMeetingProtocolService().commitApplyTask(flowTaskId, content, procinstId, nextTasksList, isCommit, shareReference, request);
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			returnMsg="操作失败，原因："+e.getMessage();
		}
		FlowContextUtil.setReturnMsgAttr(request, returnMsg);
		return new ModelAndView(FlowContextUtil.JSP_SUCCESS);
	}
	
	
	private Map initAppData(HttpServletRequest request){
		String procinstId=request.getParameter("procinstId");
		ShareReference shareReference=getMeetingProtocolService().getMeetingProtocolDao().getByPID(procinstId);
		Map map=new HashMap();
		map.put("dataOne", shareReference);
		List attachList=getMeetingProtocolService().getAttachDAO().findAttachList(ShareReference.class.getName(), shareReference.getId().toString());
		map.put("attachList", attachList);
		return map;
	}
	
	public ModelAndView commitEndProcess(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String procinstId=request.getParameter("procinstId");
		getMeetingProtocolService().commitEndProcess(procinstId);
		FlowContextUtil.setReturnMsgAttr(request, "已成功结束此需求单！");
		return new ModelAndView(FlowContextUtil.JSP_SUCCESS);
	}
	
	
	public ModelAndView showInfo(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// TODO Auto-generated method stub
		String procinstId=request.getParameter("procinstId");
		ProcessInstView processInstView=getMeetingProtocolService().getProcessPvcService().getProcessInstView(Integer.valueOf(procinstId));
		FlowContextUtil.setProcessInstTaskInfo(getMeetingProtocolService().getTaskService(),processInstView,procinstId,request);
		Map dataMap=initAppData(request);
		request.setAttribute("taskView", processInstView);
		//统计已经阅，未阅人数
		int totalReport1=0;
		int totalReport2=0;
		StringBuilder bf1=new StringBuilder();
		StringBuilder bf2=new StringBuilder();
		for (ProcTranRecord obj : processInstView.getFlowTaskList()) {
			if("03".equals(obj.getTaskType())){
				if(obj.getTransactTime()!=null){
					totalReport1++;
					bf1.append(obj.getTransactor().getName()+"、");
				}else{
					totalReport2++;
					bf2.append(obj.getTransactor().getName()+"、");
				}
			}
		}
		dataMap.put("totalReport1", totalReport1);
		dataMap.put("totalReport2", totalReport2);
		
		dataMap.put("detailReport1", bf1.toString());
		dataMap.put("detailReport2", bf2.toString());
		return new ModelAndView(basePath+"showInfo.jsp",dataMap);
	}
	
	public MeetingProtocolService getMeetingProtocolService() {
		return meetingProtocolService;
	}

	public void setMeetingProtocolService(MeetingProtocolService meetingProtocolService) {
		this.meetingProtocolService = meetingProtocolService;
	}

	
	
	
}
